#include <iostream>
#include <string.h>
#include <thread>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
using namespace std;
extern "C"
{
#include "sandbox/runner.h"
}


void inspector(const char* FIFO)
{
    const int BUFFER_SIZE = 2048;
    int open_mode = O_RDONLY;
    int bytes_read = 0;
    char buffer[BUFFER_SIZE + 1];
    int res;
    memset(buffer, '\0', sizeof(buffer));

    printf("Process %d opening FIFO O_RDONLY\n", getpid());
    int pipe_fd = open(FIFO, open_mode);
    printf("Process %d opened fd %d\n", getpid(), pipe_fd);
    if(pipe_fd != -1)
    {
        int i = 0;
        while(res = read(pipe_fd, buffer, BUFFER_SIZE) > 0){
            bytes_read += res;
            cout<<"第"<< ++i <<"次数据："<< buffer << endl;
        }
        perror("FIFO关闭");
        close(pipe_fd);
    }
    else
    {
        exit(EXIT_FAILURE);
    }
    printf("Process %d finished, %d bytes read\n", getpid(), bytes_read);
    exit(EXIT_SUCCESS);
}

int main()
{
    char* path = "user.out";
    int haha;
    if(access(path, F_OK) == -1)
    {
        haha = mkfifo(path, 0777);
        if(haha != 0)
        {
            fprintf(stderr, "Could not create fifo %s\n", path);
            exit(EXIT_FAILURE);
        }
    }
    config conn = {
        10000,              //max cpu time
        10000*10,           //max real time
        128*1024*1024,      //max memory
        32*1024*1024,       //max stack
        200,                //max process number
        10000,              //max output size
        0,                  //mem limit check only
        "/usr/bin/python3", //exec path
        NULL,               //input path
        "user.out",               //output path
        NULL,               //error path
        {"python3","hello.py"}, //args
        NULL,               //env
        "log.out",          //log path
        "general",          //seccomp rule name
        0,                  //uid
        0                   //gid
    };
    result res;
    thread deal(inspector, path);
    deal.detach();
    run(&conn, &res);
    cout<< "运行完毕"<<endl;
    cout<<"cpu time: "<<res.cpu_time<<"\r\nreal time is: " << res.real_time << "\r\nmemory used: "<< res.memory<<endl;
    cout<<"exit code: "<<res.exit_code<< "\r\nerrno is: "<<res.error<<endl;
    if(res.error != 0) cout << strerror(res.error)<<endl;  
    return 0;
}